﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

<html>
采购订单反填修改
</html>
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <title>采购订单</title>
    <style>

        .upload-btn {
            padding: 8px 15px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            white-space: nowrap;
        }

            .upload-btn:hover {
                background-color: #40a9ff;
            }



        /* 选择按钮样式 */
        .select-link {
            display: flex;
            align-items: center;
        }

            .select-link input {
                flex: 1;
                margin-right: 8px;
            }

        .select-btn {
            padding: 8px 15px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            white-space: nowrap;
        }

            .select-btn:hover {
                background-color: #40a9ff;
            }

        /* 对话框样式 */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
        }

        .modal-dialog {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 800px;
            max-width: 90%;
            max-height: 80vh;
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
            z-index: 1001;
            flex-direction: column;
        }

        .modal-content {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .modal-header {
            padding: 16px 24px;
            border-bottom: 1px solid #e8e8e8;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

            .modal-header h3 {
                margin: 0;
                font-size: 18px;
                color: rgba(0, 0, 0, 0.85);
            }

        .close-btn {
            font-size: 20px;
            color: rgba(0, 0, 0, 0.45);
            cursor: pointer;
        }

            .close-btn:hover {
                color: rgba(0, 0, 0, 0.75);
            }

        .modal-body {
            padding: 24px;
            flex: 1;
            overflow-y: auto;
        }

        .search-box {
            display: flex;
            margin-bottom: 16px;
        }

            .search-box input {
                flex: 1;
                padding: 8px 12px;
                border: 1px solid #d9d9d9;
                border-radius: 4px;
            }

        .search-btn {
            margin-left: 8px;
            padding: 8px 15px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

            .search-btn:hover {
                background-color: #40a9ff;
            }

        .table-container {
            overflow-x: auto;
        }

        .supplier-table {
            width: 100%;
            border-collapse: collapse;
        }

            .supplier-table th,
            .supplier-table td {
                padding: 12px 16px;
                border-bottom: 1px solid #e8e8e8;
                text-align: left;
            }

            .supplier-table th {
                background-color: #fafafa;
                font-weight: 500;
                color: rgba(0, 0, 0, 0.85);
            }

            .supplier-table tbody tr:hover {
                background-color: #f5f5f5;
            }

        .modal-footer {
            padding: 16px 24px;
            border-top: 1px solid #e8e8e8;
            text-align: right;
        }

        .btn-primary {
            padding: 8px 15px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

            .btn-primary:hover {
                background-color: #40a9ff;
            }

        .btn-secondary {
            padding: 8px 15px;
            margin-left: 8px;
            background-color: white;
            color: rgba(0, 0, 0, 0.65);
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
        }

            .btn-secondary:hover {
                color: #1890ff;
                border-color: #1890ff;
            }
        /* 整体布局和样式 */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            color: #333;
        }

        h2, h3 {
            margin-bottom: 20px;
            color: #444;
        }

        .form-section, .material-section {
            border: 1px solid #ddd;
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 4px;
            background-color: #fff;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
        }

        .form-field {
            margin-bottom: 15px;
        }

            .form-field label {
                display: block;
                margin-bottom: 5px;
                font-weight: 600;
                color: #555;
            }

            .form-field input,
            .form-field select,
            .form-field textarea {
                width: 100%;
                padding: 8px;
                border: 1px solid #ddd;
                border-radius: 4px;
                font-size: 14px;
            }

                .form-field input:focus,
                .form-field select:focus,
                .form-field textarea:focus {
                    border-color: #007BFF;
                    outline: none;
                    box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
                }

            .form-field textarea {
                height: 60px;
                resize: vertical;
            }

            .form-field .select-link {
                display: flex;
                align-items: center;
            }

                .form-field .select-link a {
                    margin-left: 8px;
                    color: #007BFF;
                    white-space: nowrap;
                    text-decoration: none;
                    font-size: 13px;
                }

                    .form-field .select-link a:hover {
                        text-decoration: underline;
                    }

        .action-buttons, .material-buttons {
            text-align: right;
            margin-bottom: 20px;
        }

            .action-buttons button,
            .material-buttons button {
                padding: 8px 15px;
                border: none;
                border-radius: 4px;
                cursor: pointer;
                margin-left: 10px;
                font-size: 14px;
                transition: background-color 0.2s;
            }

        .save-button {
            background-color: #007BFF;
            color: white;
        }

            .save-button:hover {
                background-color: #0069d9;
            }

        .cancel-button {
            background-color: #6c757d;
            color: white;
        }

            .cancel-button:hover {
                background-color: #5a6268;
            }

        .audit-button {
            background-color: #28a745;
            color: white;
        }

            .audit-button:hover {
                background-color: #218838;
            }

        .reverse-audit-button {
            background-color: #6c757d;
            color: white;
        }

            .reverse-audit-button:hover {
                background-color: #5a6268;
            }

        .collapse-button {
            background-color: #6c757d;
            color: white;
        }

            .collapse-button:hover {
                background-color: #5a6268;
            }

        .material-buttons button {
            background-color: #17a2b8;
            color: white;
        }

            .material-buttons button:hover {
                background-color: #138496;
            }

        .remark-field {
            grid-column: span 4;
        }

        /* 物料信息表格样式 */
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 14px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 10px;
            text-align: left;
        }

        th {
            background-color: #f8f9fa;
            font-weight: 600;
            color: #495057;
        }

        tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        tr:hover {
            background-color: #f1f1f1;
        }

        .deleteBtn {
            padding: 5px 10px;
            background-color: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
        }

            .deleteBtn:hover {
                background-color: #c82333;
            }

        table input[type="text"],
        table input[type="date"] {
            width: 100%;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        table a {
            color: #007BFF;
            text-decoration: none;
            margin-right: 5px;
            font-size: 13px;
        }

            table a:hover {
                text-decoration: underline;
            }
    </style>
</head>

<body>
    <h2>采购订单</h2>
    <div class="action-buttons">
        <button id="saveBtn" class="save-button">修改</button>
        <button id="Btn" class="save-button">采购明细</button>
        <button class="cancel-button">取消</button>
        <button id="auditBtn">审核</button>
        <button id="reverseAuditBtn">反审核</button>
        <button class="collapse-button">收起</button>
    </div>
         
	<div class="form-section">

        <input type="hidden" id="purchaseOrderId" name="purchaseOrderId">
		<div class="form-grid">
			<!-- Row 1 -->
			<div class="form-field">
				<label for="orderCode">单据编码:</label>
				<input type="text" id="documentCode" name="documentCode" placeholder="自动生成的编码" disabled>
			</div>

			<div class="form-field">

				<label class="layui-form-label">业务类型</label>
				<div class="layui-input-block">
					<select id="documentid" name="documentid" class="layui-select">
						<option value="0">--请选择部门--</option>
					</select>
				</div>
			</div>


			<div class="form-field">
				<label for="auditor">操作员:</label>
				<input type="text" id="auditor" name="auditor" placeholder="请输入操作员">
			</div>

			<div class="form-field">
				<label for="supplier">供方:</label>
				<div class="select-link">
					<input type="text" id="supplier" name="supid" placeholder="请选择供方" readonly>
					<button type="button" id="selectSupplierBtn">选择</button>
				</div>
			</div>

			<!-- Row 2 -->
			<div class="form-field">
				<label for="orderDate">单据日期:</label>
				<input type="date" id="documentStatus" name="documentStatus">
			</div>
			<div class="form-field">
				<label for="orderType">单据类型:</label>
				<select id="purchasingDe" name="purchasingDe">
					<option value="采购订单">采购订单</option>
				</select>
			</div>
			<div class="form-field">
				<label for="auditDate">审核员:</label>
				<input type="text" id="auditDate" name="auditDate" placeholder="请输入审核员">
			</div>
			<div class="form-field">
				<label for="arrivalDate">到货日期:</label>
				<input type="date" id="arrivalDate" name="arrivalDate" placeholder="选择日期">
			</div>

			<!-- Row 3 -->
			<div class="form-field">
				<label for="orderStatus">单据状态:</label>
				<input type="text" id="businessStatus" name="businessStatus" value="开立" readonly>
			</div>

			<div class="form-field">
				<label for="purchaseDepartment">采购部门:</label>
				<select id="purchasingid" name="purchasingid">
					<option value="升阳公司总经办">升阳公司总经办</option>
					<option value="升阳公司市场部">升阳公司市场部</option>
					<option value="升阳公司采购部">升阳公司采购部</option>
					<option value="升阳公司销售部门">升阳公司销售部门</option>
					<option value="升阳公司生产运营中心">升阳公司生产运营中心"</option>
				</select>
			</div>

			<div class="form-field">
                <label for="materialData">审核日期:</label>
                <input type="date" id="materialData" name="materialData" placeholder="请选择日期">
			</div>

			<div class="form-field">
				<label for="purchaseContract">采购合同:</label>
				<div class="select-link">
					<input type="text" id="purchaseContract" name="purchaseContract" placeholder="请上传采购合同">
					<button type="button" class="upload-btn">上传</button>
					<input type="file" id="fileUploadInput" accept=".pdf" style="display: none;">
				</div>
			</div>

			<!-- Row 4 -->
			<div class="form-field">
				<label for="businessStatus">业务状态:</label>
				<select id="businessType" name="businessType">
					<option value="正常">正常</option>
					<option value="挂起">挂起</option>
					<option value="手工关闭">手工关闭</option>
					<option value="系统关闭">系统关闭</option>

				</select>
			</div>
			<div class="form-field">
				<label for="operator">采购人员:</label>
				<select id="operator" name="operator">
					<option value="0">请选择</option>
                    <option value="王五">王五</option>
				</select>
			</div>
			<div class="form-field">
				<label for="materialDemand">用料需求:</label>
				<select id="materialRire" name="materialRire" disabled>
					<option value="订单用料">订单用料</option>
				</select>
			</div>
			<div class="form-field">
				<!-- Empty cell for alignment -->
				<div class="form-field remark-field">
					<label for="remark">备注信息:</label>
					<textarea id="remarksInfor" name="remarksInfor" rows="3"></textarea>
				</div>
			</div>

			<!-- Row 5 - Remark (full width) -->

		</div>
	</div>

	<!-- 物料信息部分 -->
	<div class="material-section">
		<h3>物料信息</h3>
		<div class="material-buttons">
			<button id="addRowBtn">引入</button>
			<button id="newMaterialBtn">新增物料</button>
		</div>
		<table id="materialTable">
			<thead>
				<tr>
					<th>序号</th>
					<th>跟单编号</th>
					<th>计划单号</th>
					<th>物料编码</th>
					<th>物料名称</th>
					<th>数量</th>
                    <th>单价</th>
                    <th>金额</th>
                    <th>到货数量</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>


    <!-- 供方选择对话框 -->
    <div id="supplierDialog" class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3>选择供方</h3>
                <span class="close-btn">&times;</span>
            </div>
            <div class="modal-body">
                <div class="search-box">
                    <label>供方名称</label>
                    <input type="text" id="SupplierName">
                    <label>业务联系人</label>
                    <input type="text" id="Bines">
                    <button id="searchSupplierBtn" class="search-btn" onclick="loadSuppliers()">搜索</button>
                </div>
                <div class="table-container">
                    <table class="supplier-table">
                        <thead>
                            <tr>
                                <th width="100px">序号</th>
                                <th width="100px">供应商名称</th>
                                <th>电话</th>
                                <th width="120px">业务联系人</th>
                                <th width="120px">手机号</th>
                                <th width="120px">状态</th>
                                <th width="120px">操作</th>
                            </tr>
                        </thead>
                        <tbody id="supplierList">
                            <!-- 供方数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button id="confirmSupplierBtn" class="btn-primary">确定</button>
                <button id="cancelSupplierBtn" class="btn-secondary">取消</button>
            </div>
        </div>





    </div>


    <!-- 物料选择对话框 -->
    <div id="materialDialog" class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h3>选择物料</h3>
                <span class="close-btn" onclick="closeMaterialDialog()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="table-container">
                    <table class="supplier-table">
                        <thead>
                            <tr>
                                <th width="120px">物料编码</th>
                                <th>物料名称</th>
                                <th width="150px">型号规格</th>
                                <th width="80px">主计量</th>
                                <th width="80px">操作</th>
                            </tr>
                        </thead>
                        <tbody id="materialList">
                            <!-- 物料数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-primary" onclick="confirmMaterialSelection()">确定</button>
                <button class="btn-secondary" onclick="closeMaterialDialog()">取消</button>
            </div>
        </div>
    </div>

    <div id="modalOverlay" class="modal-overlay"></div>



    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>


            var id = '@ViewBag.PurchaseOrderId';
            console.log("通过ViewBag获取的ID:", id);

           // 绑定采购明细按钮点击事件
            $('#Btn').on('click', function () {
                // 替换为实际的跳转 URL
            //window.location.href = 'http://localhost:5223/Procurements/mathPriclist';
            window.location.href = 'http://localhost:8056/Procurements/mathPriclist';
            });



            function loadRoleData() {
                layer.load(2);
                var params = {
                    document: $('[name="document"]').val(),
                    documentCode: $('[name="documentCode"]').val(), // 修正参数名
                    supid: $('[name="supid"]').val(),
                    materialName: $('[name="materialName"]').val(),
                    enddate: $('[name="enddate"]').val(),
                    modeDateStart: $('[name="modeDateStart"]').val(),
                    modeDateEnd: $('[name="modeDateEnd"]').val(),
                }

                $.ajax({
                    //url: 'http://localhost:5234/api/PurchaseInvoice/GetPurchaseorderlsit',
                    url: "@ViewBag.BaseUrl/T7/PurchaseInvoice/GetPurchaseorderlsit",
                    data: params,
                    type: 'get',
                    dataType: 'json',
                    success: function (res) {
                        console.log(res.data);
                        layer.closeAll('loading');
                        if (res.code === 210) {
                            table.reload('ID-table-demo-filter', { // 修正表格id
                                data: res.data,
                            });
                        }
                        else {
                            layer.msg('获取数据失败: ' + (res.message || '未知错误'), { icon: 2 });
                        }
                    },
                    error: function (xhr, status, error) {
                        layer.closeAll('loading');
                        layer.msg('请求失败: ' + error, { icon: 2 });
                        console.error('Ajax请求失败:', xhr.responseText);
                    }
                });
            }



                // 保存采购订单
        function savePurchaseOrder() {
            // 1. 收集表单数据
            const formData = {
                purchaseOrderId:$('#purchaseOrderId').val(),
                documentCode:$('#documentCode').val(),
                documentStatus:$('#documentStatus').val(),
                businessStatus:$('#businessStatus').val(),
                businessType:$('#businessType').val(),
                documentid:$('#documentid').val(),
                purchasingDe:$('#purchasingDe').val(),
                purchasingid:$('#purchasingid').val(),
                operator:   $('#operator').val(),
                auditor:   $('#auditor').val(),
                auditDate:   $('#auditDate').val(),
                materialData:   $('#materialData').val(),
                materialRire:   $('#materialRire').val(),
                supid:$('#supplier').val(),
                arrivalDate:  $('#arrivalDate').val(),
                purchaseContract:   $('#purchaseContract').val(),
                remarksInfor:   $('#remarksInfor').val(),
                materials_Infos: []
            };
            
            // 2. 收集物料数据
            $('#materialTable tbody tr').each(function() {
                const row = $(this);
                formData.materials_Infos.push({

                    materialsInfoid:0,
                    saleCode:"",
                    document: row.find('td:eq(1) input').val(),
                    documentStatus: row.find('td:eq(2) input').val(),
                    materialid: row.find('td:eq(3) input').val(),
                    materialName: row.find('td:eq(4) input').val(),
                    modelSper: row.find('td:eq(5) input').val(),
                    modePrimary: row.find('td:eq(6) input').val(),
                    modeDate: row.find('td:eq(7) input').val(),
                    modeQuantity: row.find('td:eq(8) input').val(),
                    modeUnitPrice: row.find('td:eq(9) input').val(),
                    modeAmount: row.find('td:eq(10)').text(),
                    modeReceived: row.find('td:eq(11) input').val(),
                    modePurchase:"无"
                });

                   // 打印每一行物料数据，检查是否正确获取
        console.log("物料数据：", formData);
            });



            if (formData.materials_Infos.length === 0) {
                alert('请至少添加一条物料信息');
                return;
            }

            // 4. 显示加载状态
            const saveBtn = $('#saveBtn');
            saveBtn.prop('disabled', true).html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate"></i> 保存中...');

            // 5. 发送AJAX请求
            $.ajax({
                //url: 'http://localhost:5090/api/PurchaseInvoices/UpdatePurc',
                url: "@ViewBag.BaseUrl/T8/PurchaseInvoices/UpdatePurc",
                type: 'post',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function(res) {
                    if (res.code === 206) {
                        alert('保存成功');
                        // 如果需要跳转或刷新页面
                        // window.location.href = '/procurement/list';
                    } else {
                        alert('保存失败: ' + res.message);
                    }
                },
                error: function(xhr, status, error) {
                    alert('保存出错: ' + error);
                },
                complete: function() {
                    saveBtn.prop('disabled', false).text('保存');
                }
            });
        }

        // 绑定保存按钮点击事件
        $(document).ready(function() {
            $('#saveBtn').click(savePurchaseOrder);
        });



        // 全局变量，存储当前编辑的行
        let currentEditingRow = null;

        // 物料对话框相关函数
        function openMaterialDialog(row) {
            currentEditingRow = row;
            document.getElementById('materialDialog').style.display = 'block';
            document.getElementById('modalOverlay').style.display = 'block';
            loadMaterials();
        }

        function closeMaterialDialog() {
            document.getElementById('materialDialog').style.display = 'none';
            document.getElementById('modalOverlay').style.display = 'none';
            currentEditingRow = null;
        }

        function loadMaterials() {
            $.ajax({
                //url: "http://localhost:5234/api/Materials/GetMatern_Code",
                url: "@ViewBag.BaseUrl/T7/Materials/GetMatern_Code",
                type: "GET",
                dataType: "json",
                success: function (res) {
                    if (res.code === 0) {
                        var html = '';
                        res.data.forEach(item => {
                            html += `<tr>
                                        <td>${item.materialid}</td>
                                        <td>${item.materialName}</td>
                                        <td>${item.measurement}</td>
                                        <td>${item.primaryUnit}</td>
                                        <td>
                                            <button type="button" class="select-btn"
                                                onclick="selectMaterialItem('${item.materialid}', '${item.materialName.replace(/'/g, "\\'")}', '${item.measurement.replace(/'/g, "\\'")}', '${item.primaryUnit.replace(/'/g, "\\'")}')">
                                                选择
                                            </button>
                                        </td>
                                    </tr>`;
                        });
                        $('#materialList').html(html);
                    }
                },
                error: function (xhr, status, error) {
                    console.error("加载物料数据失败:", error);
                }
            });
        }

        function selectMaterialItem(materialid, materialName, measurement, primaryUnit) {
            if (currentEditingRow) {
                // 填充当前行的物料信息
                currentEditingRow.cells[3].querySelector('input').value = materialid;
                currentEditingRow.cells[4].querySelector('input').value = materialName;
                currentEditingRow.cells[5].querySelector('input').value = measurement;
                currentEditingRow.cells[6].querySelector('input').value = primaryUnit;
            }
            closeMaterialDialog();
        }









          function confirmMaterialSelection() {
              const selected = $('input[name="materialRadio"]:checked');
              if (selected.length > 0 && currentMaterialInput) {
                  const row = currentMaterialInput.closest('tr');

                  // 填充物料信息到当前行
                  row.cells[3].querySelector('input').value = selected.data('code');
                  row.cells[4].querySelector('input').value = selected.data('name');
                  row.cells[5].querySelector('input').value = selected.data('spec');
                  row.cells[6].querySelector('input').value = selected.data('unit');

                  closeMaterialDialog();
              } else {
                  alert('请先选择物料');
              }
          }

          // 修改addTableRow函数中的物料编码单元格
          function addTableRow() {
              const tbody = materialTable.querySelector('tbody');
              const rowCount = tbody.rows.length;
              const newRow = tbody.insertRow();

              // ... 其他单元格代码保持不变 ...

              // 物料编码（修改后的版本）
              const cell4 = newRow.insertCell(3);
              cell4.innerHTML = '<div class="select-link"><input type="text"><button onclick="selectMaterial(this)">选择物料</button></div>';

              // ... 剩余代码保持不变 ...
          }

          document.addEventListener('DOMContentLoaded', function () {
              const uploadBtn = document.querySelector('.upload-btn');
              const fileInput = document.getElementById('fileUploadInput');
              const textInput = document.getElementById('purchaseContract');

              uploadBtn.addEventListener('click', function () {
                  fileInput.click();
              });

              fileInput.addEventListener('change', function (e) {
                  const file = e.target.files[0];
                  if (file) {
                      textInput.value = file.name;
                      // 这里可以添加进一步上传文件到服务器的代码，比如使用fetch或axios等
                  }
              });
          });

          document.addEventListener('DOMContentLoaded', function () {
              // 获取DOM元素
              const selectBtn = document.getElementById('selectSupplierBtn');
              const modal = document.getElementById('supplierDialog');
              const overlay = document.getElementById('modalOverlay');
              const closeBtn = document.querySelector('.close-btn');
              const cancelBtn = document.getElementById('cancelSupplierBtn');
              const confirmBtn = document.getElementById('confirmSupplierBtn');
              const searchBtn = document.getElementById('searchSupplierBtn');
              const supplierInput = document.getElementById('supplier');

              // 显示对话框
              selectBtn.addEventListener('click', function () {
                  modal.style.display = 'block';
                  overlay.style.display = 'block';
                  loadSuppliers(); // 加载供方数据
              });

              // 关闭对话框的几种方式
              [closeBtn, cancelBtn, overlay].forEach(el => {
                  el.addEventListener('click', function () {
                      modal.style.display = 'none';
                      overlay.style.display = 'none';
                  });
              });

              // 阻止点击对话框内容时关闭
              modal.addEventListener('click', function (e) {
                  e.stopPropagation();
              });

              // 确定选择
              confirmBtn.addEventListener('click', function () {
                  const selectedRadio = document.querySelector('input[name="supplierRadio"]:checked');
                  if (selectedRadio) {
                      const supplierName = selectedRadio.getAttribute('data-name');
                      supplierInput.value = supplierName;
                      modal.style.display = 'none';
                      overlay.style.display = 'none';
                  } else {
                      alert('请先选择一个供方');
                  }
              });

              // 搜索功能
              searchBtn.addEventListener('click', function () {
                  const keyword = document.getElementById('supplierSearch').value.trim();
                  loadSuppliers(keyword);
              });

              ///回车键搜索
              // document.getElementById('supplierSearch').addEventListener('keypress', function (e) {
              //     if (e.key === 'Enter') {
              //         searchBtn.click();
              //     }
              // });
          });

          // 获取按钮和表格的引用
        const addRowBtn = document.getElementById('addRowBtn');
        const newMaterialBtn = document.getElementById('newMaterialBtn');
        const materialTable = document.getElementById('materialTable');



            // 修改addTableRow函数
        function addTableRow() {
            const tbody = materialTable.querySelector('tbody');
            const rowCount = tbody.rows.length;
            const newRow = tbody.insertRow();

            // 序号
            const cell1 = newRow.insertCell(0);
            cell1.textContent = rowCount + 1;

            // 跟单编号
            const cell2 = newRow.insertCell(1);
            cell2.innerHTML = '<input type="text">';

            // 计划单号
            const cell3 = newRow.insertCell(2);
            cell3.innerHTML = '<input type="text">';

            // 物料编码
            const cell4 = newRow.insertCell(3);
            cell4.innerHTML = '<input type="text"><button type="button" class="select-btn" onclick="openMaterialDialog(this.parentNode.parentNode)">选择物料</button>';

            // 物料名称
            const cell5 = newRow.insertCell(4);
            cell5.innerHTML = '<input type="text">';

            // 型号规格
            const cell6 = newRow.insertCell(5);
            cell6.innerHTML = '<input type="text">';

            // 主计量
            const cell7 = newRow.insertCell(6);
            cell7.innerHTML = '<input type="text">';

            // 需求日期
            const cell8 = newRow.insertCell(7);
            cell8.innerHTML = '<input type="date" placeholder="请选择日期">';

            // 数量
            const cell9 = newRow.insertCell(8);
            cell9.innerHTML = '<input type="text">';

            // 单价
            const cell10 = newRow.insertCell(9);
            cell10.innerHTML = '<input type="text">';

            // 金额
            const cell11 = newRow.insertCell(10);
            cell11.textContent = '0.00';

            // 到货数量
            const cell12 = newRow.insertCell(11);
            cell12.innerHTML = '<input type="text">';

            // 操作列（删除按钮）
            const cell13 = newRow.insertCell(12);
            const deleteBtn = document.createElement('button');
            deleteBtn.className = 'deleteBtn';
            deleteBtn.textContent = '删除';
            cell13.appendChild(deleteBtn);

            // 为新添加的删除按钮绑定点击事件
            deleteBtn.addEventListener('click', function() {
                tbody.removeChild(newRow);
                // 重新编号所有行
                const rows = tbody.rows;
                for (let i = 0; i < rows.length; i++) {
                    rows[i].cells[0].textContent = i + 1;
                }
            });
        }








          // 为新增行按钮绑定点击事件
          addRowBtn.addEventListener('click', addTableRow);
          newMaterialBtn.addEventListener('click', addTableRow);

          // 为已有的删除按钮绑定点击事件
          document.querySelectorAll('.deleteBtn').forEach(btn => {
              btn.addEventListener('click', function () {
                  const row = this.closest('tr');
                  const tbody = row.parentNode;
                  tbody.removeChild(row);

                  // 重新编号所有行
                  const rows = tbody.rows;
                  for (let i = 0; i < rows.length; i++) {
                      rows[i].cells[0].textContent = i + 1;
                  }
              });
          });

          function loadSuppliers() {
              var supplierName = $("#SupplierName").val();
              var bines = $("#Bines").val();
              $.ajax({
                  //url: "http://localhost:5234/api/MateSuppli/GetMateria",
                url: "@ViewBag.BaseUrl/T7/MateSuppli/GetMateria",
                  data: {
                      SupplierName: supplierName,
                      Bines: bines
                  },
                  type: "GET",
                  dataType: "json",
                  async: false,
                  success: function (res) {
                      var str = ``;
                      if (res.code === 210) {
                          res.data.forEach(function (item) {
                              // 模糊匹配示例，假设对供方名称和业务联系人进行匹配
                              if (supplierName && item.supplierName.indexOf(supplierName) === -1) {
                                  return;
                              }
                              if (bines && item.businessContact.indexOf(bines) === -1) {
                                  return;
                              }
                              str += `<tr>
                                          <td>${item.supid}</td>
                                          <td>${item.supplierName}</td>
                                          <td>${item.telephone}</td>
                                          <td>${item.bines}</td>
                                          <td>${item.financialPhone}</td>
                                          <td>${item.status}</td>
                                          <td>
                                                <button type="button" class="select-btn" onclick="selectSupplier('${item.supplierName}')">选择</button>
                                          </td>
                                      </tr>`;
                          });
                      }
                      console.log(res);
                      $("#supplierList").html(str);
                  },
                  error: function (xhr, status, error) {
                      console.error("加载供方数据失败:", error);
                  }
              });
          }

          function selectSupplier(supplierName) {
              // 获取主页面中显示供方名称的输入框
              const supplierInput = document.getElementById('supplier');
              supplierInput.value = supplierName;
              // 关闭对话框，这里假设你有关闭对话框的相关逻辑函数，比如hideSupplierDialog
              hideSupplierDialog();
          }

          function hideSupplierDialog() {
              const modal = document.getElementById('supplierDialog');
              const overlay = document.getElementById('modalOverlay');
              modal.style.display = 'none';
              overlay.style.display = 'none';
          }

                      // ==================== 加载业务类型下拉选项=================================
        $(document).ready(function() {
            $.ajax({
                //url: "http://localhost:5234/api/Procurements/GetDocument",
                url: "@ViewBag.BaseUrl/T7/Procurements/GetDocument",
                type: "GET",
                success: function(res) {
                    if (res.code === 210) {
                        var options = '<option value="0">--请选择业务类型--</option>';
                        res.data.forEach(item => {
                            options += `<option value="${item.documentid}">${item.documentidName}</option>`;
                        });
                        $('[name="documentid"]').html(options);
                        var encodedData = getUrlParameter('data');
                        if (encodedData) {
                            try {
                                var data = JSON.parse(decodeURIComponent(encodedData));
                                document.getElementById('documentid').value = data.documentid || '';
                            } catch (error) {
                                console.error('解析数据时出错:', error);
                            }
                        }
                    }
                },
                error: function(xhr, status, error) {
                    console.error("加载业务类型失败:", error);
                }
            });
        });




             function getUrlParameter(name) {
            name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.search);
            return results === null? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
        }

        // 日期格式转换函数
        function formatDate(dateStr) {
            if (!dateStr) return '';
            const date = new Date(dateStr);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }

        window.onload = function () {
            var encodedData = getUrlParameter('data');
            if (encodedData) {
                try {
                    var data = JSON.parse(decodeURIComponent(encodedData));

                    // 赋值给表单字段
                    document.getElementById('purchaseOrderId').value = data.purchaseOrderId || '';
                    document.getElementById('documentCode').value = data.documentCode || '';

                    document.getElementById('documentid').value = data.documentid || '';
             
                    
                    document.getElementById('auditor').value = data.auditor || '';
                    document.getElementById('supplier').value = data.supid || '';
                    document.getElementById('documentStatus').value = formatDate(data.documentStatus);
                    document.getElementById('purchasingDe').value = data.purchasingDe || '';
                    document.getElementById('auditDate').value = data.auditDate || '';

                    document.getElementById('arrivalDate').value = formatDate(data.arrivalDate);

                    document.getElementById('businessStatus').value = data.businessStatus || '';
                    document.getElementById('purchasingid').value = data.purchasingid || '';
                    document.getElementById('purchaseContract').value = data.purchaseContract || '';
                    document.getElementById('businessType').value = data.businessType || '';
                    document.getElementById('operator').value = data.operator || '';
                    document.getElementById('materialRire').value = data.materialRire || '';
                    document.getElementById('remarksInfor').value = data.remarksInfor || '';
                    document.getElementById('materialData').value = formatDate(data.materialData);

                    // 如果有物料数据，添加并赋值给物料表格
                    // 由于传递的数据没有 materials_Infos 数组，将单独的物料信息作为一条记录处理
                    if (data.materialid) {
                        addTableRow();
                        var lastRow = document.querySelectorAll('#materialTable tbody tr')[document.querySelectorAll('#materialTable tbody tr').length - 1];
                        lastRow.cells[1].querySelector('input').value = data.document || '';
                        lastRow.cells[2].querySelector('input').value = data.documentStatuss || '';
                        lastRow.cells[3].querySelector('input').value = data.materialid || '';
                        lastRow.cells[4].querySelector('input').value = data.materialName || '';
                        lastRow.cells[5].querySelector('input').value = data.modelSper || '';
                        lastRow.cells[6].querySelector('input').value = data.modePrimary || '';
                        lastRow.cells[7].querySelector('input').value = formatDate(data.modeDate);
                        lastRow.cells[8].querySelector('input').value = data.modeQuantity || '';
                        lastRow.cells[9].querySelector('input').value = data.modeUnitPrice || '';
                        lastRow.cells[10].textContent = data.modeAmount || '0.00';
                        lastRow.cells[11].querySelector('input').value = data.modeReceived || '';
                    }
                } catch (error) {
                    console.error('解析数据时出错:', error);
                }
            }
        };


         // 审核按钮点击事件
            $('#auditBtn').on('click', function() {
                var purchaseOrderId = $('#purchaseOrderId').val();
                  var businessStatus = $('#businessStatus').val();
                    var auditDate = $('#auditDate').val();


                if (confirm('确定要审核此单据吗？')) {
                    $.ajax({
                        //url: 'http://localhost:5090/api/Procurements/UpdateAlpe',
                    url: "@ViewBag.BaseUrl/T8/Procurements/UpdateAlpe",
                    type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            purchaseOrderId: purchaseOrderId,
                            businessStatus:businessStatus,
                             auditDate:auditDate,
                        }),
                        success: function(response) {
                            if (response.code === 206) {
                                alert('审核成功');
                                // 刷新页面或更新状态
                                location.reload();
                            } else {
                                alert('审核失败: ' + response.message);
                            }
                        },
                        error: function(xhr, status, error) {
                            // console.error('审核请求失败:', error);
                            alert('审核请求失败，请检查网络连接');
                        }
                    });
                }
            });

            // 反审核按钮点击事件
            $('#reverseAuditBtn').on('click', function() {
                   var purchaseOrderId = $('#purchaseOrderId').val();
                  var businessStatus = $('#businessStatus').val();
                    var auditDate = $('#auditDate').val();


                if (confirm('确定要反审核此单据吗？')) {
                    $.ajax({
                        //url: 'http://localhost:5090/api/Procurements/UpdateAlpe',
                        url: "@ViewBag.BaseUrl/T8/Procurements/UpdateAlpe",
                    type: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            purchaseOrderId: purchaseOrderId,
                            businessStatus:businessStatus,
                             auditDate:auditDate,
                        }),
                        success: function(response) {
                            if (response.code === 206) {
                                alert('反审核成功');
                                // 刷新页面或更新状态
                                location.reload();
                            } else {
                                alert('反审核失败: ' + response.message);
                            }
                        },
                        error: function(xhr, status, error) {
                            // console.error('反审核请求失败:', error);
                            alert('反审核请求失败，请检查网络连接');
                        }
                    });
                }
            });



    </script>
</body>
</html>


